package com.gzstv.dlnasdk;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;

public class DLNAApplication extends Application {

    private static final String TAG = "DLNAApplication";
    private static final String PREFS_NAME = "DLNAAppPrefs";
    private static final String KEY_LAST_CRASH_INFO = "last_crash_info";

    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            private Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);
                String crashInfo = sw.toString();

                Log.e(TAG, "Uncaught exception in thread " + thread.getName() + ":\n" + crashInfo);

                // Save crash info to SharedPreferences
                SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                prefs.edit().putString(KEY_LAST_CRASH_INFO, crashInfo).commit();

                // Restart the app (or go to a specific error activity)
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                // Let the default handler do its work (e.g., show crash dialog, log to system)
                if (defaultUEH != null) {
                    defaultUEH.uncaughtException(thread, ex);
                }
            }
        });
    }

    public static String getLastCrashInfo(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_LAST_CRASH_INFO, null);
    }

    public static void clearLastCrashInfo(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().remove(KEY_LAST_CRASH_INFO).apply();
    }
}